﻿using AWSV2.Services;
using Common.HardwareSDKS.FFmpeg;
using Common.Utility.AJ;
using Common.Utility;
using LiveChartsCore;
using Stylet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows;
using System.IO;
using LiveChartsCore.SkiaSharpView;
using SkiaSharp;
using IWshRuntimeLibrary;
using Common;

namespace AWSV2.ViewModels
{
    public class SplashScreenViewModel : Screen
    {
        private string _message;
        public string Message { get => _message; set => SetAndNotify(ref _message, value); }

        private BackgroundWorker _worker;
        private IWindowManager _windowManager;
        private IEventAggregator _eventAggregator;

        public SplashScreenViewModel(IWindowManager windowManager, IEventAggregator eventAggregator)
        {
            _windowManager = windowManager;
            _eventAggregator = eventAggregator;

            AJStyletService.Instance().Init(windowManager, eventAggregator);

            Message = I18NService.Translate(LangKeys.正在启动);

            _worker = new BackgroundWorker
            {
                WorkerReportsProgress = true,
            };

            _worker.DoWork += Worker_DoWork;

            _worker.RunWorkerCompleted += Worker_RunWorkerCompleted;

            _worker.ProgressChanged += Worker_ProgressChanged;

            var timer = new System.Timers.Timer()
            {
                Interval = TimeSpan.FromSeconds(1.5).TotalMilliseconds,
                AutoReset = false
            };

            timer.Elapsed += (_, __) =>
            {
                timer.Stop();
                _worker.RunWorkerAsync();
            };

            timer.Start();

        }

        private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            Message = e.UserState as string;
        }

        private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //  _eventAggregator.PublishOnUIThread(new SplashScreenEvent());
            Application.Current.Dispatcher.Invoke(() =>
            {
                _windowManager.ShowWindow(new LoginViewModel(_windowManager, _eventAggregator));
                RequestClose();
            });
        }

        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                _worker.ReportProgress(0, I18NService.Translate(LangKeys.检测激活信息));
                // 程序启动, 赋值机器码
                CloudAPI.MACHINEMD5 = AJUtil.MachineMD5();

                Thread.Sleep(200);

                _worker.ReportProgress(0, I18NService.Translate(LangKeys.注册编码支持));

                //// TODO: 测试激活码
                //CloudAPI.MACHINEMD5 = "be9f3d59265cd18e09ed66b9fdf4366e";

                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

                Thread.Sleep(200);

                _worker.ReportProgress(0, I18NService.Translate(LangKeys.初始化ID生成器));

                YidService.Init();

                //var a = $"{DateTime.Now.Date.AddDays(7)}_{CloudAPI.MACHINEMD5}_{YitIdHelper.NextId()}".AESEncrypt(Common.Properties.Resources.AESKey).Base64Encrypt();

                Thread.Sleep(600);

                _worker.ReportProgress(0, I18NService.Translate(LangKeys.启动数据库服务));

                // 启动数据库服务
                AJDatabaseService.Start();

                Thread.Sleep(600);

                _worker.ReportProgress(0, I18NService.Translate(LangKeys.启动网络服务));

                // 启动webapi
                AJWebAPIHostService.StartAsync();

                //var providerDetails = Common.SyncData.GetServiceProvider();
                //AWSV2.Globalspace.Provicer = providerDetails;
                //AWSV2.Globalspace.ProvicerTitle = $"{providerDetails.service_products}  |  {providerDetails.company_name}  服务热线：{providerDetails.mobile}";

                //2023-05-18 新增应用程序快捷方式创建

                string QuickName = Application.ResourceAssembly.GetName().Name;
                //string QuickName1 = "篮圈AVS1修复工具";
                var appAllPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
                //var systemStartPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
                var systemStartPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

                if (!System.IO.File.Exists(Path.Combine(systemStartPath, string.Format("{0}.lnk", QuickName))))
                {
                    Thread.Sleep(200);

                    _worker.ReportProgress(0, I18NService.Translate(LangKeys.创建桌面快捷方式));

                    CreateShortcut(systemStartPath, QuickName, appAllPath, QuickName);
                }
                //if (!System.IO.File.Exists(Path.Combine(systemStartPath, string.Format("{0}.lnk", QuickName1))))
                //{
                //    appAllPath = appAllPath.Replace(QuickName, QuickName1);
                //    CreateShortcut(systemStartPath, QuickName1, appAllPath, QuickName1);
                //}

                AWSV2.Globalspace.Provicer = new Common.Model.Custom.ServiceProvider();
                AWSV2.Globalspace.ProvicerTitle = I18NService.Translate(LangKeys.正在加载中);

                #region 注册 FFMPEG --阿吉 2024年4月12日09点18分

                Thread.Sleep(200);

                _worker.ReportProgress(0, I18NService.Translate(LangKeys.加载视频解码组件));

                FFmpegBinariesHelper.RegisterFFmpegBinaries();

                //FFmpegUtil.ConfigureHWDecoder();

                #endregion

                #region 定时任务处理逻辑

                Thread.Sleep(200);

                _worker.ReportProgress(0, I18NService.Translate(LangKeys.初始化定时任务));

                Task.Run(async () =>
                {
                    await TimedTask.Run();
                });

                #endregion

            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine($"初始启动存在异常:{ex.Message}");
                System.Diagnostics.Trace.WriteLine(ex.StackTrace);
            }

            Thread.Sleep(200);

            _worker.ReportProgress(0, I18NService.Translate(LangKeys.初始化Excel导出组件));

            Common.Utility.ExcelHelper.Instance.Init();

            Thread.Sleep(200);

            _worker.ReportProgress(0, I18NService.Translate(LangKeys.初始化图表组件));

            LiveCharts.Configure(cfg =>
            {
                if (I18NService.IsZhCN)
                {
                    cfg.HasGlobalSKTypeface(SKFontManager.Default.MatchCharacter("Microsoft YaHei", '汉'));
                }
            });
        }

        /// <summary>
        ///  向目标路径创建指定文件的快捷方式
        /// </summary>
        /// <param name="directory">目标目录</param>
        /// <param name="shortcutName">快捷方式名字</param>
        /// <param name="targetPath">文件完全路径</param>
        /// <param name="description">描述</param>
        /// <param name="iconLocation">图标地址</param>
        /// <returns>成功或失败</returns>
        private bool CreateShortcut(string directory, string shortcutName, string targetPath, string description = null, string iconLocation = null)
        {
            try
            {
                if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);                         //目录不存在则创建
                                                                                                                //添加引用 Com 中搜索 Windows Script Host Object Model
                string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));          //合成路径
                WshShell shell = new IWshRuntimeLibrary.WshShell();
                IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath);    //创建快捷方式对象
                shortcut.TargetPath = targetPath;                                                               //指定目标路径
                shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);                                  //设置起始位置
                shortcut.WindowStyle = 1;                                                                       //设置运行方式，默认为常规窗口
                shortcut.Description = description;                                                             //设置备注
                shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation;    //设置图标路径
                shortcut.Save();                                                                                //保存快捷方式
                return true;
            }
            catch (Exception ex)
            {
                string temp = ex.Message;
                temp = "";
            }
            return false;
        }
    }

}
